package com.kiell.gulimall.product.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.kiell.gulimall.product.entity.AttrEntity;
import com.kiell.gulimall.product.service.AttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiell.common.utils.PageUtils;
import com.kiell.common.utils.Query;

import com.kiell.gulimall.product.dao.ProductAttrValueDao;
import com.kiell.gulimall.product.entity.ProductAttrValueEntity;
import com.kiell.gulimall.product.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param collect
     */
    @Override
    public void saveProductAttr(List<ProductAttrValueEntity> collect) {
        this.saveBatch(collect);
    }

    /**
     * @param spuId
     * @return
     */
    @Override
    public List<ProductAttrValueEntity> baseAttrListForspu(Long spuId) {
        List<ProductAttrValueEntity> entities = this.baseMapper.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        if (!entities.isEmpty()){
            entities = entities.stream().map(m->{
                AttrEntity byId = attrService.getById(m.getAttrId());
                if (byId != null){
                    m.setValueType(byId.getValueType());
                }
                return m;
            }).collect(Collectors.toList());
        }
        return entities;
    }

    /**
     * @param spuId
     * @param entities
     */
    @Transactional
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities) {
        //1.删除spu之前对应的所有属性
        this.baseMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));
        List<ProductAttrValueEntity> collect = entities.stream().map(m -> {
            m.setSpuId(spuId);
            return m;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }






}